package org.example.memora.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import lombok.RequiredArgsConstructor;
import org.example.memora.common.result.Result;
import org.example.memora.common.utils.UserHolder;
import org.example.memora.entity.CommunityJoinApplication;
import org.example.memora.entity.CommunityUser;
import org.example.memora.mapper.CommunityJoinApplicationMapper;
import org.example.memora.mapper.CommunityUserMapper;
import org.example.memora.service.CommunityJoinApplicationService;
import org.springframework.web.bind.annotation.*;
import io.swagger.v3.oas.annotations.tags.*;
import io.swagger.v3.oas.annotations.Parameter;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/community/applications")
@RequiredArgsConstructor
@Tag(name = "社群加群申请", description = "管理用户的社群加群申请：提交、审核、查询等")
public class CommunityJoinApplicationController {

    private final CommunityJoinApplicationService applicationService;
    private final CommunityUserMapper communityUserMapper;
    private final CommunityJoinApplicationMapper applicationMapper;

    @Operation(summary = "用户提交加群申请", description = "用户填写理由后申请加入指定社群")
    @Parameters({
            @Parameter(name = "communityId", description = "社群ID", required = true, in = ParameterIn.QUERY),
            @Parameter(name = "reason", description = "申请理由", required = true, in = ParameterIn.QUERY)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "申请提交成功"),
            @ApiResponse(responseCode = "400", description = "重复申请或参数错误"),
            @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @PostMapping("/apply")
    public Result<?> applyToJoin(@RequestParam Long communityId,
                                 @RequestParam String reason) {
        Long userId = UserHolder.getUser().getUserId();
        boolean success = applicationService.applyToJoinCommunity(communityId, userId, reason);
        return success ? Result.success() : Result.error("已申请或正在审核中");
    }

    @Operation(summary = "获取待审核申请列表", description = "群主查看某个社群下的所有待处理加群申请")
    @Parameter(name = "communityId", description = "社群ID", required = true, in = ParameterIn.QUERY)
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "403", description = "无权限查看"),
            @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/pending")
    public Result<List<CommunityJoinApplication>> getPendingApplications(@RequestParam Long communityId) {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("未登录");
        }
        CommunityUser communityUser = communityUserMapper.selectByCommunityIdAndUserId(communityId, userId);
        if (communityUser == null ||!"owner".equals(communityUser.getRole())) {
            return Result.error("无权限");
        }
        List<CommunityJoinApplication> applications = applicationService.getPendingApplications(communityId);
        return Result.success(applications);
    }
    @Operation(
            summary = "获取所有拥有社群的待审核申请列表",
            description = "群主查看自己所拥有的所有社群中的待处理加群申请"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功"),
            @ApiResponse(responseCode = "403", description = "无权限查看"),
            @ApiResponse(responseCode = "500", description = "服务器错误")
    })
    @GetMapping("/pendingAll")
    public Result<List<CommunityJoinApplication>> getPendingApplicationsAll() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("未登录");
        }

        List<Long> communityIds = communityUserMapper.selectDistinctCommunityIdsByRoleAndUserId("owner", userId);
        if (communityIds.isEmpty()) {
            return Result.error("无权限");
        }

        List<CommunityJoinApplication> applications = new ArrayList<>();

        for (Long communityId : communityIds) {
            List<CommunityJoinApplication> pendingApps = applicationService.getPendingApplications(communityId);
            if (pendingApps != null && !pendingApps.isEmpty()) {
                applications.addAll(pendingApps);
            }
        }

        return Result.success(applications);
    }


    @Operation(summary = "审核加群申请", description = "群主批准或拒绝用户加入社群的申请")
    @Parameters({
            @Parameter(name = "applicationId", description = "申请ID", required = true, in = ParameterIn.QUERY),
            @Parameter(name = "status", description = "审核状态：APPROVED 或 REJECTED", required = true, in = ParameterIn.QUERY)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "审核处理成功"),
            @ApiResponse(responseCode = "400", description = "状态参数非法"),
            @ApiResponse(responseCode = "500", description = "处理失败或申请不存在")
    })
    @PostMapping("/review")
    public Result<?> reviewApplication(@RequestParam Long applicationId,
                                       @RequestParam String status) {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("未登录");
        }
        Long communityId = applicationMapper.selectCommunityIdById(applicationId);
        CommunityUser communityUser = communityUserMapper.selectByCommunityIdAndUserId(communityId, userId);
        if (communityUser == null ||!"owner".equals(communityUser.getRole())) {
            return Result.error("无权限");
        }
        if (!"APPROVED".equalsIgnoreCase(status) && !"REJECTED".equalsIgnoreCase(status)) {
            return Result.error("无效状态");
        }
        boolean success = applicationService.reviewApplication(applicationId, status.toUpperCase());
        return success ? Result.success() : Result.error("处理失败或申请不存在");
    }
    @Operation(summary = "退出社群", description = "当前用户主动退出指定社群，群主不可退出")
    @Parameters({
            @Parameter(name = "communityId", description = "社群ID", required = true, in = ParameterIn.QUERY)
    })
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "退出成功"),
            @ApiResponse(responseCode = "400", description = "未加入社群或群主不可退出"),
            @ApiResponse(responseCode = "500", description = "服务器处理失败")
    })
    @PostMapping("/leave")
    public Result<?> leaveCommunity(@RequestParam Long communityId) {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("未登录");
        }

        CommunityUser record = communityUserMapper.selectByCommunityIdAndUserId(communityId, userId);
        if (record == null) {
            return Result.error("你未加入该社群");
        }

        if ("owner".equalsIgnoreCase(record.getRole())) {
            return Result.error("群主不可退出社群");
        }

        int deleted = communityUserMapper.deleteByCommunityIdAndUserId(communityId, userId);
        return deleted > 0 ? Result.success() : Result.error("退群失败，请重试");
    }
}
